package lumis.portal.serialization.persistency.fs;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import lumis.portal.serialization.persistency.IDirectory;
import lumis.portal.serialization.persistency.IFSDirectory;
import lumis.util.FileUtil;

/**
 * {@link IDirectory} implementation that uses a file system's directory as the concrete repository.
 * 
 * @version $Revision: 8804 $ $Date: 2008-01-22 16:41:47 -0200 (Tue, 22 Jan 2008) $
 * @since 4.0.10
 */
public class FSDirectory implements IFSDirectory
{
	protected File rootFile;
	
	public FSDirectory(String rootPath)
	{
		this(new File(rootPath));
	}

	public FSDirectory(File root)
	{
		super();
		this.rootFile = root;
	}

	public InputStream getInputStream(String filePath) throws FileNotFoundException, IOException
	{
		return new FileInputStream(new File(rootFile, filePath));
	}

	public OutputStream getOutputStream(String filePath) throws IOException
	{
		File file = new File(rootFile, filePath);
		
		if (!file.exists())
		{
			// make sure that the parent exists
			File parentFile = file.getParentFile();
			if (!parentFile.exists() && !parentFile.mkdirs())
				throw new IllegalStateException("Error creating dirs to '" + filePath + "'");

			file.createNewFile();
		}
		return new FileOutputStream(file);
	}

	public void close() throws IOException
	{
	}

	public boolean exists(String filePath) throws IOException
	{
		return (new File(rootFile, filePath)).exists();
	}

	public String getDescription()
	{
		return this.getClass().getName() + " rootPath=" + rootFile.getAbsolutePath();
	}

	public void delete() throws IOException
	{
		try
		{
			FileUtil.deleteDir(rootFile.getAbsolutePath(), true);
		}
		catch (Exception expected)
		{
			throw new IOException("Could not delete Directory " + getDescription());
		}	
	}

	public String getDirectoryPath()
	{
		return rootFile.getAbsolutePath();
	}
}
